/**
 * @author walter.fan@gmail.com on 07/18/06
 */
package cn.fanyamin.web.struts;

import java.util.List;
import java.util.Map;


import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.fanyamin.business.ItemService;
import cn.fanyamin.business.TaskService;
import cn.fanyamin.business.UserService;
import cn.fanyamin.domain.UserCategory;
import cn.fanyamin.domain.Context;
import cn.fanyamin.domain.Goal;
import cn.fanyamin.domain.Item;
import cn.fanyamin.domain.Module;
import cn.fanyamin.domain.Role;
import cn.fanyamin.domain.Task;
import cn.fanyamin.domain.User;
import cn.fanyamin.util.collection.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * DOCUMENT ME!
 *
 * @author $author$
 * @version $Revision: 1.2 $
 */
public abstract class SecureBaseAction extends BaseAction {
    
    private static final Log logger = LogFactory.getLog(SecureBaseAction.class);
    /**
     * DOCUMENT ME!
     *
     * @param mapping DOCUMENT ME!
     * @param form DOCUMENT ME!
     * @param request DOCUMENT ME!
     * @param response DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    final public ActionForward execute(
        ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
            throws java.lang.Exception {
        
    	User user = getUserFromSession(request);
        if(user == null) {
            user = getUserFromCookie(request);
            if(user == null) {
                logger.info("Not found user in session or cookie");
                return mapping.findForward("login");
            } else {
                UserService userService = getWebApp().getUserService();
                List<User> uList = userService.find(user);
                if(CollectionUtils.isEmpty(uList)) {
                    logger.info("Not found user in cookie: " + user);
                    return mapping.findForward("login");
                } 
                user = uList.get(0);
                HttpSession session = request.getSession();
                session.setAttribute("sess_user", user);   
            }
        }
        
        String link = getLinkFromRequest(request);
        Role aRole = user.getRole();
        //logger.debug("current role is " + aRole);
        Module aModule = aRole.getModuleByLink(link);
        
        if(aModule == null) {
         	request.setAttribute("errormsg",  "Do not have privilege to access " 
         			+ aModule + " with " + link
         			+"<br/>role: " + aRole);
        	return mapping.findForward("error");
        } else {
        	request.getSession().setAttribute("sess_module", aModule);
        	return super.execute(mapping, form, request, response);
        }
    }

	private String getLinkFromRequest(HttpServletRequest request) {
		String link = request.getRequestURI();
        String query = request.getQueryString();
        if(StringUtils.isNotEmpty(query)) {
            link = link + "?" + query;
        }
        
        if(StringUtils.startsWith(link, "/pims/")) {
            link = link.substring(6);
        } else if(StringUtils.startsWith(link, "/")) {
            link = link.substring(1);
        }
 
        logger.info(" enter " + link);
		return link;
	}
    
    protected User getUserFromSession(HttpServletRequest request) {
    	return (User)request.getSession().getAttribute("sess_user");
    }

    protected void setCategories(HttpServletRequest request, int categoryType) {
    	User user = getUserFromSession(request);
        ItemService itemService = getWebApp().getItemService();
        Map<Integer, UserCategory> categories = itemService.getCategories(categoryType, user.getUserID());
        request.setAttribute("categories", categories);
    }
    
    protected void setContexts(HttpServletRequest request) {
        TaskService taskService = getWebApp().getTaskService();
        Map<Integer, Context> contexts = taskService.getContexts();
        request.setAttribute("contexts", contexts);
    }

    protected void setItemTypes(HttpServletRequest request) {
        Map<Integer,String> map = Item.getItemTypes();
        request.setAttribute("itemTypes",map);
    }
    
    protected void setGoalTypes(HttpServletRequest request) {
        Map<Integer,String> map = Goal.getGoalTypes();
        request.setAttribute("goalTypes",map);
    }
    
    protected void setTaskTypes(HttpServletRequest request) {
        Map<Integer,String> map = Task.getTaskTypes();
        request.setAttribute("taskTypes",map);
    }

}

